﻿using System;
using System.Linq;
using System.Web;
using System.Web.Routing;

namespace CodeContrib.Web.Routing
{
	// http://dotnetslackers.com/articles/aspnet/Implementing-RESTful-Routes-and-Controllers-in-ASP-NET-MVC-2-0.aspx
	public class RestfulHttpMethodConstraint : HttpMethodConstraint
	{
		public RestfulHttpMethodConstraint(params string[] allowedMethods) : base(allowedMethods)
		{
		}

		protected override bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
		{
			if (routeDirection == RouteDirection.UrlGeneration)
			{
				var verb = "GET";

				if (values.ContainsKey(parameterName))
				{
					verb = values[parameterName].ToString();
				}

				return AllowedMethods.Any(x => x.Equals(verb, StringComparison.OrdinalIgnoreCase));
			}

			return base.Match(httpContext, route, parameterName, values, routeDirection);
		}
	}
}